package com.github.niefy.modules.wx.handler;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.niefy.modules.wx.entity.WxUserSubMsg;
import com.github.niefy.modules.wx.entity.WxUserSubMsgLog;
import com.github.niefy.modules.wx.service.WxUserSubMsgLogService;
import com.github.niefy.modules.wx.service.WxUserSubMsgService;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.sql.Timestamp;
import java.util.LinkedList;
import java.util.Map;
import java.util.stream.Collectors;

import static me.chanjar.weixin.common.api.WxConsts.EventType.*;

/**
 * @author : [86188]
 * @description : 订阅消息事件处理
 * @createTime : [2023/1/30 9:18]
 * @updateUser : [86188]
 * @updateTime : [2023/1/30 9:18]
 */
@Component
public class SubscribeMsgHandler extends AbstractHandler {

    @Autowired
    WxUserSubMsgService wxUserSubMsgService;
    @Autowired
    WxUserSubMsgLogService wxUserSubMsgLogService;

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMpXmlMessage, Map<String, Object> map,
                                    WxMpService wxMpService, WxSessionManager wxSessionManager) {
        this.logger.info("订阅通知事件推送--"
                + "OPENID:" + wxMpXmlMessage.getFromUser()
                + "事件类型" + wxMpXmlMessage.getEvent()
        );
        //用户操作订阅通知弹窗，若同意订阅，当前用户当前模板记录为生效（wx_user_sub_template_msg）
        if (wxMpXmlMessage.getEvent().equals(SUBSCRIBE_MSG_POPUP_EVENT)){
            popupHandle(wxMpXmlMessage);
        }
        //用户在服务通知管理页面做通知管理时，取消了某个订阅通知，
        //原记录（wx_user_sub_template_msg）删除，归入log表
        if (wxMpXmlMessage.getEvent().equals(SUBSCRIBE_MSG_CHANGE_EVENT)){
            changeHandle(wxMpXmlMessage);
        }
        //向用户发送过订阅通知成功后，原记录（wx_user_sub_template_msg）删除，归入log表
        //现只有一次订阅可用，故这样操作，若未来微信放开长期订阅，发送长期订阅消息则原记录依然生效，记log表
        //TODO 回调事件信息若显式发送失败，则将发送订阅通知的log(wx_sub_template_msg_log)记录删除
        if (wxMpXmlMessage.getEvent().equals(SUBSCRIBE_MSG_SENT_EVENT)){
            sentHandle(wxMpXmlMessage);
        }
        return null;
    }

    void popupHandle(WxMpXmlMessage wxMpXmlMessage){
        var list = wxMpXmlMessage.getSubscribeMsgPopupEvent().getList();
        //仅记录用户同意订阅的通知
        var popupEventList =
                list.stream().filter(item -> "accept".equals(item.getSubscribeStatusString())).collect(Collectors.toList());
        var wxUserSubMsgs = new LinkedList<WxUserSubMsg>();
        popupEventList.forEach((item -> {
            var queryEntity = WxUserSubMsg.builder()
                    .appid(wxMpXmlMessage.getToUser())
                    .fromUser(wxMpXmlMessage.getFromUser())
                    .templateId(item.getTemplateId())
                    .build();
            var one = wxUserSubMsgService.getOne(new QueryWrapper<>(queryEntity));
            if (BeanUtil.isEmpty(one)){
                var wxUserSubMsg = WxUserSubMsg.builder()
                        .appid(wxMpXmlMessage.getToUser())
                        .fromUser(wxMpXmlMessage.getFromUser())
                        .createTimestamp(new Timestamp(wxMpXmlMessage.getCreateTime()))
                        .templateId(item.getTemplateId())
                        .popupScene(item.getPopupScene())
                        .build();
                wxUserSubMsgs.add(wxUserSubMsg);
            }
        }));
        wxUserSubMsgService.saveBatch(wxUserSubMsgs);
    }

    void changeHandle(WxMpXmlMessage wxMpXmlMessage){
        var list = wxMpXmlMessage.getSubscribeMsgChangeEvent().getList();
        var changeEventList = list.stream().filter(item -> "reject".equals(item.getSubscribeStatusString())).collect(Collectors.toList());

        var insWxUserSubMsgLogs = new LinkedList<WxUserSubMsgLog>();
        //删增
        changeEventList.forEach(item -> {
            var delWxUserSubMsg = WxUserSubMsg.builder()
                    .appid(wxMpXmlMessage.getToUser())
                    .fromUser(wxMpXmlMessage.getFromUser())
                    .templateId(item.getTemplateId())
                    .build();
            wxUserSubMsgService.remove(new QueryWrapper<WxUserSubMsg>(delWxUserSubMsg));
            var insWxUserSubMsgLog = WxUserSubMsgLog.builder()
                    .appid(wxMpXmlMessage.getToUser())
                    .fromUser(wxMpXmlMessage.getFromUser())
                    .templateId(item.getTemplateId())
                    .subscribeStatus(item.getSubscribeStatusString())
                    .createTimestamp(new Timestamp(wxMpXmlMessage.getCreateTime()))
                    .build();
            insWxUserSubMsgLogs.add(insWxUserSubMsgLog);
        });
        wxUserSubMsgLogService.saveBatch(insWxUserSubMsgLogs);
    }

    void sentHandle(WxMpXmlMessage wxMpXmlMessage){
        var list = wxMpXmlMessage.getSubscribeMsgSentEvent().getList();
        var sentEventList = list.stream().filter(item -> "0".equals(item.getErrorCode())).collect(Collectors.toList());
        var insWxUserSubMsgLogs = new LinkedList<WxUserSubMsgLog>();
        sentEventList.forEach(item -> {
            var delWxUserSubMsg = WxUserSubMsg.builder()
                    .appid(wxMpXmlMessage.getToUser())
                    .fromUser(wxMpXmlMessage.getFromUser())
                    .templateId(item.getTemplateId())
                    .build();
            wxUserSubMsgService.remove(new QueryWrapper<WxUserSubMsg>(delWxUserSubMsg));
            var insWxUserSubMsgLog = WxUserSubMsgLog.builder()
                    .appid(wxMpXmlMessage.getToUser())
                    .fromUser(wxMpXmlMessage.getFromUser())
                    .templateId(item.getTemplateId())
                    .subscribeStatus("sent")
                    .createTimestamp(new Timestamp(wxMpXmlMessage.getCreateTime()))
                    .build();
            insWxUserSubMsgLogs.add(insWxUserSubMsgLog);
        });
        wxUserSubMsgLogService.saveBatch(insWxUserSubMsgLogs);

    }
}
